#include <iostream>
#include <string>
#include "InetAddr.hpp"
#include "common.hpp"
#include "log.hpp"
#include <cerrno>
#include <cstring>
using namespace LogMudule;
using namespace Inet;
int main(int argc, char *argv[])
{
  if (argc != 3)
  {
    LOG(LogLevel::ERROR) << "请输入正确的IP地址和端口号";
    Die(ARGC_ERR);
  }
  std::string ip = argv[1];
  uint16_t port = std::stoi(argv[2]);
  int sockfd = socket(AF_INET, SOCK_STREAM, 0);
  if (sockfd < 0)
  {
    LOG(LogLevel::FATAL) << "socket:" << strerror(errno);
    Die(SOCKET_ERR);
  }
  struct sockaddr_in srever_addr;
  bzero(&srever_addr, sizeof(srever_addr));
  srever_addr.sin_addr.s_addr = ::inet_addr(ip.c_str());
  srever_addr.sin_family = AF_INET;
  srever_addr.sin_port = htons(port);

  int n = ::connect(sockfd, CONV(&srever_addr), sizeof(srever_addr));
  if (n == 0)
  {
    while (true)
    {
      std::cout << "请输入你要发送的内容: ";
      std::string message;
      getline(std::cin, message);
      n = write(sockfd, message.c_str(), message.size());
      if (n > 0)
      {
        char inbuffer[4096];
        int m = ::read(sockfd, inbuffer, sizeof(inbuffer));
        if (m > 0)
        {
          inbuffer[m] = 0;
          std::cout << inbuffer << std::endl;
        }
        else
          break;
      }
      else
        break;
    }
  }
  ::close(sockfd);
  return 0;
}